<?php
	// MSSQL
	// Database class by cuzco
	// Found from php.net
	//
	// Date: 4.10.2006
	//
	error_reporting(E_ALL);
	
	// Include DataSource interface	
	require_once("DataSource.php");
	
	class MSSQL extends DataSource
	{
		// Connection variable
		private $db_connection;
		
		public function MSSQL($serverName, $userName, $passWord, $dbName="")
		{
			if($this->db_connection)
			{
				$this->Close();
			}
			
			$this->Connect($serverName, $userName, $passWord, $dbName);
		}
		
		// Connect
		// Connects to given datasource, optionally select database on connect
		public function Connect($serverName, $userName, $passWord, $dbName="")
		{
			$this->db_connection = mssql_connect($serverName, $userName, $passWord, $dbName="");
			
			if($this->db_connection && strlen($dbName) > 0)
			{
				mssql_select_db($dbName);
			}
			
			return ($this->db_connection != FALSE ? TRUE : FALSE);
		}
		
		// Close
		// Close the connection
		public function Close()
		{
			return mssql_close($this->db_connection);
		}
		
		// SelectDB
		// Select a database to be used
		public function SelectDB($dbName)
		{
			return mssql_select_db($dbName);
		}
		
		// Query
		// Does a database query. Return values depends in query
		public function Query($sql)
		{
			$query_result = mssql_query($sql, $this->db_connection);
			
			if(stripos($sql, 'insert') === false && $query_result !== true)
			{
				$result = array();
				while($row = mssql_fetch_object($query_result))
				{
					$result[] = $row;
				}
				
				mssql_free_result($query_result);
				
				return $result;
			}
			else
			{
				if(is_resource($query_result))
				{
					mssql_free_result($query_result);
				}
				
				$query = 'select SCOPE_IDENTITY() AS last_insert_id';
				$query_result = mssql_query($query);
				
				$query_result = mssql_fetch_object($query_result);
				
				if(is_resource($query_result))
				{
					mssql_free_result($query_result);
				}
				
				return $query_result->last_insert_id;
			}
		}
	}
?>